<template>
	<view class="xin-calendar css-theme" :class="[cueTheme]"   >
		<view class="calendar-control" v-if="showHeader">
			<!-- <view class="calendar-control-left" @click="pre()" >
				<view class="tn-icon-left" style="float: left;padding-left: 20px;font-size: 12px;font-weight: bolder"></view>
			</view> -->
			<view class="calendar-control-center" style="font-weight: bolder;padding-left: 30rpx;font-size: 18px;">
				{{activeDay.substring(0,7).replace("-","年")}}月
			</view>
			<!-- <view class="calendar-control-right " @click="next()">
				<view class="tn-icon-right" style="float: right;padding-right: 20px;font-size: 12px;font-weight: bolder"></view>
			</view> -->
		</view>
		<view class="calendar-header">
			<view class="calendar-week" v-for="(item, index) in weeks" :key="index">{{ item }}</view>
		</view>
		<view class="calendar-body">
			<swiper class="swiper" :current="current" circular adjust-height="highest" :autoplay="false"
				:indicator-dots="false" :interval="3000" :duration="500" @change="swiperChange"
				@animationfinish1="swiperChange">
				<swiper-item class="swiper-item" v-for="(calendar, calendarIndex) in calendarList" :key="calendarIndex">
					<view class="calendar-line" v-for="(line, lineIndex) in calendar.dateList" :key="lineIndex">
						<view class="calendar-day" v-for="(item, index) in line" :key="index"
							@click="clickEvent(item, index)">

							<view :class="['day-item', {
							  can: item.type === 'day',
							  pre: item.type === 'pre',
							  next: item.type === 'next',
							  today: today === item.date,
							  active: activeDay === item.date,
							}]" v-if="getType(item.date)==0" style="color:#07C160;">
								<view class="label" v-if="nowTime == item.date">今</view>
								<view class="label" v-else>{{item.day}}</view>
							</view>

							<!-- 月经 -->
							<view :class="['day-item', {
								  can: item.type === 'day',
								  pre: item.type === 'pre',
								  next: item.type === 'next',
								  today: today === item.date,
								  active: activeDay === item.date,
								}]" v-if="getType(item.date)==8" style="background-image: linear-gradient(to bottom,#FC865D,#ED5150);color: white;">
								<view class="label" v-if="nowTime == item.date">今</view>
								<view class="label" v-else>{{item.day}}</view>
							</view>
							<!-- 预测月经 -->
							<view :class="['day-item', {
								  can: item.type === 'day',
								  pre: item.type === 'pre',
								  next: item.type === 'next',
								  today: today === item.date,
								  active: activeDay === item.date,
								}]" v-if="getType(item.date)==1 " style="background-color:#FFC6E6;color: white;">
								<view class="label" v-if="nowTime == item.date">今</view>
								<view class="label" v-else>{{item.day}}</view>
							</view>
							<view :class="['day-item', {
									  can: item.type === 'day',
									  pre: item.type === 'pre',
									  next: item.type === 'next',
									  today: today === item.date,
									  active: activeDay === item.date,
									}]" v-if="getType(item.date)==2" style="color:#FF9F14;">
								<view class="label" v-if="nowTime == item.date">今</view>
								<view class="label" v-else>{{item.day}}</view>
								
							</view>

							<view :class="['day-item', {
										  can: item.type === 'day',
										  pre: item.type === 'pre',
										  next: item.type === 'next',
										  today: today === item.date,
										  active: activeDay === item.date,
										}]" v-if="getType(item.date)==3" style="color:#FF9F14;">
								<view class="label" v-if="nowTime == item.date">今</view>
								<view class="label" v-else>{{item.day}}</view>
								<view style="font-size: 6px;position:absolute;bottom: -10px;" class="tn-icon-star-fill"></view>
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>
	</view>
</template>

<script>
	import moment from 'moment'
	import XinTagBtn from './xin-tag-btn.vue'
	import lunar from './lunar'
	var _self
	export default {
		components: {
			XinTagBtn,
		},
		props: {
			value: {
				type: String,
				default: moment().format('YYYY-MM-DD'),
			},
			background: {
				type: String,
				default: '#ffffff'
			},
			showHeader: {
				type: Boolean,
				default: false
			},
			dots: {
				type: Array,
				default: () => [],
			},
			lunar: {
				type: Boolean,
				default: true,
			},
			festival: {
				type: Boolean,
				default: true,
			},
			changeStatus:{
				type: Boolean,
				default: true,
			},
			changeStatusGo:{
				type: Boolean,
				default: true,
			}
		},
		data() {
			return {
				weeks: ['日', '一', '二', '三', '四', '五', '六', ],
				dateList: [],
				today: moment().format('YYYY-MM-DD'),
				activeDay: moment().format('YYYY-MM-DD'),
				current: 1,
				calendarList: [{
						date: moment().add(-1, 'months').startOf('month').format('YYYY-MM'),
						dateList: [],
					},
					{
						date: moment().startOf('month').format('YYYY-MM'),
						dateList: [],
					},
					{
						date: moment().add(1, 'months').startOf('month').format('YYYY-MM'),
						dateList: [],
					},
				],
				user: [],
				nowyear: '',
				nowmonth: '',
				nowdate: '',
				itemlist: [],
				nowTime:'',
				nowMonthTime:''
			}
		},
		computed: {},
		filters: {},
		watch: {
			value(n, o) {
				this.activeDay = n
			},
			activeDay(n, o) {
				this.$emit('input', n)
				this.$emit('change', n)
				this.init()
			},
			
			changeStatus(n,o){
				var _self=this
				setTimeout(function() {
					_self.getListForecast(_self.activeDay.substring(0, 7))
				}, 1000);
			},
			changeStatusGo(n,o){
				var _self=this
				setTimeout(function() {
					_self.getListForecast(_self.activeDay.substring(0, 7))
				}, 1000);
				
			}
		},
		mounted() {
			if (this.value) this.activeDay = this.value
			this.init()
			_self = this
			var currentDate = new Date();
			var currentYear = currentDate.getFullYear();
			var currentMonth = currentDate.getMonth()
			var currentDate = currentDate.getDate()
			_self.nowyear = currentYear;
			_self.nowmonth = currentMonth + 1 < 10 ? ("0" + (currentMonth + 1)) : (currentMonth + 1);
			_self.nowdate = currentDate < 10 ? ("0" + currentDate) :currentDate;
			this.nowTime = _self.nowyear+"-"+_self.nowmonth+"-"+_self.nowdate
			this.nowMonthTime = _self.nowyear+"-"+_self.nowmonth
			uni.getStorage({
				key: 'user',
				success: function(res) {
					if (res.data) {
						_self.user = res.data
						setTimeout(function() {
							_self.getListForecast(_self.nowyear + "-" + _self.nowmonth)
						}, 200);
					}
				},
				fail: function(e) {
					uni.navigateTo({
						url: '../login/login'
					});
				}
			})
		},
		methods: {
			getType(date) {
				var type = ""
				for (var i = 0; i < _self.itemlist.length; i++) {
					if (date == _self.itemlist[i].time) {
						if(_self.itemlist[i].menstrualRecords && _self.itemlist[i].menstrualRecords.isMenstrual==1){
							type = 8
						}else{
							type  = _self.itemlist[i].type
						}
						break;
					}
				}
				return type;
			},
			getListForecast(time) {
				// var uri = getApp().globalData.url + 'modules/menstrualForecast/appList?queryTime=' + time + '&userId=' +
				// 	this.user.id;
				
				var _self = this
				var data = {
					userId: this.user.id,
					queryTime:time
				}
				this.$api.listMenstrualForecast(data).then((res) => {
					var resData = res;
					console.log(res)
					if (resData.code == "200") {
						_self.itemlist = resData.data;
					}
				})	
				
			},
			init() {
				this.calendarList.forEach((item, index) => {
					item.dateList = this.createMonthDays(item.date)
				})
			},
			pre() {
				this.current = this.current - 1 < 0 ? 2 : this.current - 1
			},
			next() {
				this.current = this.current + 1 > 2 ? 0 : this.current + 1
			},
			clickEvent(item, index) {
				if (item.type !== 'day'){
					return
				}
				this.activeDay = item.date
				// console.log(item.date)
				// var today = new Date();
				// var otherDate = new Date(item.date); 
				
				// if (otherDate > today) {
				//     console.log("大于")
				// }else{
				// 	 console.log("小于")
				// 	this.activeDay = item.date
					
				// }
				
				
			},
			createMonthDays(date) {
				let list = [];
				let monthInfo = this.getMomentInfo(date + '-01')
				for (let i = 0; i < monthInfo.daysInMonth; i++) {
					let dd = moment(monthInfo.firstDayInMonth).add(i, 'days')
					let dayInfo = this.getMomentInfo(dd)
					let day = {
						type: 'day',
						...dayInfo,
					};
					list.push(day);
				}
				let pre = [];
				for (let i = 0; i < monthInfo.weekday; i++) {
					let dd = moment(monthInfo.firstDayInMonth).add(-(monthInfo.weekday - i), 'days')
					let dayInfo = this.getMomentInfo(dd)
					pre.push({
						type: 'pre',
						...dayInfo,
					});
				}
				let next = [];
				let length = 42 - monthInfo.weekday - monthInfo.daysInMonth;
				for (let i = 0; i < length; i++) {
					let dd = moment(monthInfo.lastDayInMonth).add(i + 1, 'days')
					let dayInfo = this.getMomentInfo(dd)
					next.push({
						type: 'next',
						...dayInfo,
					});
				}
				list = [...pre, ...list, ...next];
				let result = [];
				for (let i = 0; i < list.length; i += 7) {
					result.push(list.slice(i, i + 7));
				}
				return result;
			},
			swiperChange(e) {
				let current = e.detail.current
				let preIndex = current - 1 > -1 ? current - 1 : 2
				let nextIndex = current + 1 > 2 ? 0 : current + 1
				let preMoment = moment(this.calendarList[current].date + '-01').add(-1, 'months')
				if (preMoment.format('YYYY-MM') != moment().format('YYYY-MM')) {
					preMoment = preMoment.startOf('month')
				} else {
					preMoment = moment()
				}
				this.calendarList[preIndex].date = preMoment.format('YYYY-MM')
				let nextMoment = moment(this.calendarList[current].date + '-01').add(1, 'months')
				if (nextMoment.format('YYYY-MM') != moment().format('YYYY-MM')) {
					nextMoment = nextMoment.startOf('month')
				} else {
					nextMoment = moment()
				}
				this.calendarList[nextIndex].date = nextMoment.format('YYYY-MM')
				if (moment().format('YYYY-MM') === this.calendarList[current].date) {
					this.activeDay = moment().format('YYYY-MM-DD')
				} else {
					this.activeDay = this.calendarList[current].date + '-01'
				}
				this.$nextTick(() => {
					this.$emit('monthChange', this.activeDay)
					this.getListForecast(this.activeDay.substring(0, 7))
				})
				
				console.log(this.calendarList)
			},
			getMomentInfo(date) {
				let m = moment(date)
				return {
					moment: m,
					firstDayInMonth: moment(m).startOf('month').format('YYYY-MM-DD'),
					lastDayInMonth: moment(m).startOf('month').add(m.daysInMonth() - 1, 'days').format('YYYY-MM-DD'),
					date: m.format('YYYY-MM-DD'),
					year: m.format('YYYY'),
					month: m.format('MM'),
					day: m.format('DD'),
					weekday: m.weekday(),
					daysInMonth: m.daysInMonth(),
					stamp: Number(m.format('x')),
					lunarInfo: lunar.solar2lunar(Number(m.format('YYYY')), Number(m.format('MM')), Number(m.format('DD')))
				}
			},
		}
	}
</script>


<style lang="less">
	// 源码修改可以在这里
	// 尺寸
	@font-size: 26rpx;
	@space-width: 18rpx;
	@radius-width: 18rpx;
	// 颜色
	@color-gray: #222222;
	@color-blue: #0095ff;
	@color-green: #15bf81;
	@color-yellow: #f7ab42;
	@color-red: #ff6666;
	@color-background: #f6f7ff;

	// 方法
	.shadow (@color: @color-gray, @x: 5rpx, @y: 5rpx, @r: 15rpx, @o: 3) {
		// box-shadow: @x @y @r fade(@color, @o);
	}

	.xin-calendar {
		.calendar-control {
			display: flex;
			margin-bottom: @space-width;

			.calendar-control-left {
				flex: 1;
			}

			.calendar-control-center {
				display: flex;
				justify-content: center;
				align-items: center;
			}

			.calendar-control-right {
				flex: 1;
				text-align: right;
			}
		}

		.calendar-header {
			display: flex;

			.calendar-week {
				flex: 1;
				text-align: center;
				line-height: 60rpx;
			}
		}

		.calendar-body {
			.swiper {
				height: 460rpx;
				min-height: 460rpx;

				.swiper-item {
					height: 460rpx;
					min-height: 460rpx;

					.calendar-line {
						display: flex;

						.calendar-day {
							flex: 1;
							display: flex;
							justify-content: center;
							align-items: center;
							padding: @space-width / 2 0;

							.day-item {
								width: 60rpx;
								height: 60rpx;
								line-height: 60rpx;
								// background: @color-background;
								display: flex;
								flex-direction: column;
								justify-content: center;
								align-items: center;
								border-radius: 100%;
								transition: all 0.15s;
								position: relative;

								.label {
									font-size: @font-size;
									line-height: @font-size;
									// margin: 4rpx 0 8rpx 0;
								}

								.desc {
									font-size: @font-size - 10rpx;
									opacity: 0.5;
									line-height: @font-size - 10rpx;

									&.blue {
										color: @color-blue;
										opacity: 0.7;
									}
								}

								&.can {
									&.today {
										background: #ffffff;
										color: @color-blue;
										font-weight: bold;
										.shadow(@color: @color-gray, @o: 8);

										.dot {
											display: none;
										}
									}

									&.active {
										// background: @color-blue;
										color: #ffffff;
										// font-weight: bold;
										// .shadow(@color: @color-blue, @o: 50);
										border: 2px dashed #E4E4E4;
										.dot {
											display: none;
										}

										.desc {
											&.blue {
												color: #ffffff;
											}
										}
									}

									.dot {
										position: absolute;
										bottom: 2px;
										left: 50%;
										transform: translateX(-50%);
										width: 8rpx;
										height: 8rpx;
										border-radius: 100%;
										// background: @color-blue;
									}
								}

								&.pre,
								&.next {
									opacity: 0.15;
								}
							}
						}
					}
				}
			}
		}
	}
</style>